<template>
  <el-dialog
    v-model="visible"
    title="新增补单"
    width="900px"
    class="return-order-dialog"
    :before-close="close"
    :close-on-click-modal="false"
  >
    <!-- 顶部筛选条件 -->
    <el-form
      :model="form"
      :validate-on-rule-change="false"
      ref="formRef"
      label-width="80px"
      class="remark-form"
      :rules="rules"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="订单类型">
            <el-radio-group v-model="form.orderType">
              <el-radio v-for="item in orderTypeOptions" :label="item.value" :key="item.value">
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="1"> </el-col>
        <el-col :span="15">
          <el-form-item label="订单号" prop="relatedOrderId">
            <el-input v-model="form.relatedOrderId" readonly placeholder="请选择订单">
              <template #suffix>
                <el-button @click="handleQuery" type="primary" size="mini" link>选择</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 订单信息展示 -->
      <div class="info-section">
        <div class="section-title">
          <span class="label">客户信息</span>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="客户姓名">{{
              form?.receiverName || '--'
            }}</el-descriptions-item>
            <el-descriptions-item label="手机号">{{
              form?.receiverPhone || '--'
            }}</el-descriptions-item>
            <!-- 客户地址 -->
            <el-descriptions-item label="客户地址">{{
              form?.receiverAddress || '--'
            }}</el-descriptions-item>
            <el-descriptions-item label="下单时间">{{
              form?.orderTime || '--'
            }}</el-descriptions-item>
            <el-descriptions-item label="支付方式">{{ payTypeText || '--' }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="section-title">
          <span class="label">订单明细</span>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="已付金额">
              <el-tag type="success">{{ form?.actualPrice || '--' }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="代收金额">
              <el-tag type="primary">{{ form?.orderPrice || '--' }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="订单金额">
              <el-tag type="info">{{ form?.totalAmount || '--' }}</el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="section-title">
          <span class="label">产品明细</span>

          <div class="product-header">
            <span class="product-title">
              <el-text v-if="!isEmpty(packageData)" type="success" size="large"
                >套餐名称: {{ packageData.productName }}
              </el-text>
            </span>
            <el-button :icon="Link" link type="primary" @click="selectPackage"
              >从套餐选择</el-button
            >
            <span class="ml-10">
              <!-- 是否是固定套餐 用etag展示 1 是 0 否 -->
              <el-tag
                v-if="form.isFixed"
                closable
                @close="fixedClose"
                type="success"
                effect="dark"
                size="small"
                >固定套餐</el-tag
              >
              <el-tag v-else type="warning" effect="dark" size="small">普通</el-tag>
            </span>
          </div>

          <el-table style="margin-top: 10px" :data="form.productCollection" border size="small">
            <el-table-column label="产品名称" prop="productName" />
            <el-table-column
              label="产品类型"
              prop="usageType"
              width="110"
              :formatter="getGoodsTypeByUsageType"
            >
            </el-table-column>
            <el-table-column label="赠品" prop="isGift" width="60">
              <template #default="{ row }">
                <span>{{ row.isGift === 1 ? '是' : '否' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="件数" width="150">
              <template #default="{ row }">
                <el-input-number
                  v-if="!form.isFixed"
                  v-model="row.num"
                  style="width: 100%"
                  controls-position="right"
                  :min="0"
                />
                <span v-else> {{ row.num }}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column label="成本价" width="80" prop="costPrice" /> -->
            <el-table-column label="销售价" width="150" prop="productPrice">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.productPrice"
                  style="width: 100%"
                  controls-position="right"
                  :min="0"
                  v-if="!form.isFixed"
                />
                <span v-else> {{ row.productPrice }}</span>
              </template>
            </el-table-column>
          </el-table>

          <div class="total-bar">
            <span
              >合计：<b>{{ totalQty }}</b> 件 &nbsp;
              <template v-if="isEmpty(packageData)">
                <b class="amount">{{ totalAmount }}</b>
              </template>
              <!-- 套餐价 -->
              <template v-else>
                <b class="amount oldSalePrice">原价：{{ totalAmount }}</b>
                <b class="salePrice">优惠价：{{ packageData.salePrice }}</b>
              </template>
              元</span
            >
          </div>
        </div>
      </div>

      <!-- 备注 -->
      <el-row>
        <el-col :span="form.shippingType === '2' ? 12 : 24">
          <el-form-item label="物流类型" prop="shippingType">
            <!-- 单选 自主发货 和 系统物流 -->
            <el-radio-group v-model="form.shippingType">
              <el-radio v-for="item in logisticsTypeOptions" :label="item.value" :key="item.value">
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <template v-if="form.shippingType == '1'">
          <el-col :span="12">
            <el-form-item label="补单物流" prop="logisticsPlatformCode">
              <el-select
                v-model="form.logisticsPlatformCode"
                placeholder="请选择补单物流"
                clearable
                :options="logisticsCompany"
              />
            </el-form-item>
          </el-col>
        </template>
        <!-- 自主发货的时候 才需要写死物流 -->
        <template v-else>
          <el-col :span="12">
            <el-form-item label="三方物流" prop="logisticsPlatformCode">
              <el-select
                v-model="form.logisticsPlatformCode"
                placeholder="请选择补单物流"
                clearable
                :options="sysSelfFulfillmentOgistics"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="补单单号" prop="logisticsNo">
              <el-input
                v-model="form.logisticsNo"
                maxlength="20"
                show-word-limit
                placeholder="请输入补单物流单号"
                type="text"
              />
            </el-form-item>
          </el-col>
        </template>
        <el-col :span="12">
          <el-form-item label="补单类型" prop="replenishOrderType">
            <el-select
              v-model="form.replenishOrderType"
              placeholder="请选择补单类型"
              clearable
              :options="replenishTypeOptions"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="补单备注" prop="orderRemark">
        <el-input
          v-model="form.orderRemark"
          type="textarea"
          rows="3"
          placeholder="请输入补单备注"
        />
      </el-form-item>
    </el-form>

    <!-- 底部操作按钮 -->
    <template #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确认创建</el-button>
    </template>
  </el-dialog>

  <!-- 选择订单 -->
  <orderSelectionDialog
    ref="orderDialogRef"
    :type="form.orderType"
    :goodsTypes="goodsTypes"
    @select="handleOrderSelect"
  />

  <!-- 商品选择弹窗 -->
  <SelectGoodsPackage ref="selectGoodsPackageRef" @ok="selectGoodsPackage" />
</template>

<script setup lang="ts">
import { ref, reactive, defineExpose, watch, onMounted } from 'vue';
import { computed } from 'vue';
import { Link } from '@element-plus/icons-vue';
import { addRepeatPurchaseReplenishmentOrder } from '../../api/platformOrders/orders/repeatPurchaseOrder';
import { ElMessage } from 'element-plus';
import { cloneDeep, isEmpty } from 'lodash';
import { useCustomStore } from '../../store/modules/custom';

const customStore = useCustomStore();
const visible = ref(false);
const submitLoading = ref(false);
const formRef = ref();
const orderDialogRef = ref<any>();
const selectGoodsPackageRef = ref<any>();
const emits = defineEmits(['ok']);

// 改为 props
interface Option {
  value?: any;
  label?: string;
  [key: string]: any;
}

const props = withDefaults(
  defineProps<{
    orderTypeOptions?: Option[];
    replenishTypeOptions?: Option[];
    goodsList?: Option[];
    goodsTypes?: Option[];
    logisticsCompany?: Option[];
    payType?: Option[];
    sysSelfFulfillmentOgistics?: Option[];
    logisticsTypeOptions?: Option[];
  }>(),
  {
    orderTypeOptions: () => [],
    replenishTypeOptions: () => [],
    goodsList: () => [],
    goodsTypes: () => [],
    logisticsCompany: () => [],
    payType: () => [],
    sysSelfFulfillmentOgistics: () => [],
    logisticsTypeOptions: () => []
  }
);

const initField = () => ({
  // 订单类型
  orderType: '1',
  // 关联订单id
  relatedOrderId: '',
  // 订单价格
  orderPrice: 0,
  // 实付金额
  actualPrice: 0,
  // 总金额
  totalAmount: 0,
  // 订单备注
  orderRemark: '',
  // 补单类型
  replenishOrderType: '1',
  // 物流平台编码
  logisticsPlatformCode: '',
  // 物流编号
  logisticsNo: '',
  // 商品明细
  productCollection: [],
  // 支付方式
  paymentMethod: '',
  // 客户名称
  receiverName: '',
  // 客户手机号
  receiverPhone: '',
  // 客户地址
  receiverAddress: '',
  // 订单时间
  orderTime: '',
  // 配送类型默认系统物流
  shippingType: '1',
  // 是否补单 这里一定是
  isReplenishOrder: '1',
  // 不延期发货
  isDelayedDelivery: 0
});

const form = reactive<any>(initField());

// 校验规则
const getFormRules = (shippingType: any) => {
  const rules: any = {
    orderRemark: [
      {
        required: true,
        message: '请输入补单备注',
        trigger: ['blur', 'change']
      }
    ],
    logisticsPlatformCode: [{ required: true, message: '请选择系统补单物流', trigger: ['blur'] }],
    relatedOrderId: [
      {
        required: true,
        message: '请选择关联订单',
        trigger: ['change']
      }
    ]
  };

  // shippingType = '2' 的时候  单号和物流必填
  if (shippingType === '2') {
    rules.logisticsPlatformName = [
      { required: true, message: '请填写自主补单物流', trigger: ['blur'] }
    ];
    rules.logisticsNo = [{ required: true, message: '请填写自主补单物流单号', trigger: ['blur'] }];
  }

  // shippingType = '2' 的时候
  if (shippingType === '1') {
  }

  return rules;
};

const rules = computed(() => getFormRules(form.shippingType));

// 支付方式
const payTypeText = computed(
  () => props.payType.find((v: any) => v.value === form.paymentMethod)?.label || ''
);

// 监听goodslist
watch(
  () => props.goodsList,
  (newVal: any) => {
    if (newVal.length > 0) {
      form.productCollection = cloneDeep(newVal);
    }
  },
  {
    immediate: true
  }
);

watch(
  () => form.shippingType,
  (type) => {
    // 系统物流 清空自主物流
    if (type == 2) {
      form.logisticsPlatformCode = '';
      form.logisticsNo = '';
    } else {
      form.logisticsPlatformCode = '';
    }
    formRef.value.clearValidate([]);
  }
);

const handleQuery = () => {
  orderDialogRef.value.show();
};

// 选择订单
const handleOrderSelect = (row: any) => {
  form.relatedOrderId = row.orderId;
  form.orderPrice = row.orderPrice;
  form.actualPrice = row.actualPrice;
  form.totalAmount = row.totalAmount;
  form.receiverName = row.receiverName;
  form.receiverPhone = row.receiverPhone;
  form.receiverAddress = row.receiverAddress;
  form.orderTime = row.orderTime;
};

// 固定套餐商品关闭
const fixedClose = () => {
  packageData.value = {};
  form.isFixed = 0;
  const list = cloneDeep(props.goodsList);
  list.forEach((v) => {
    v.num = 0;
  });
  // 初始化套餐列表
  form.productCollection = list;
};

// 选择套餐
const packageData = ref({});
function selectGoodsPackage(goods: any) {
  packageData.value = goods;
  form.isFixed = goods.isFixed;
  // 判断商品是否固定
  // 同步数量和价格到商品列表
  goods.productCollection.forEach((item: any) => {
    item.productPrice = item.salePrice; // 这里一定要用销售价
  });
  form.productCollection = goods.productCollection;
}

const close = () => {
  visible.value = false;
  formRef.value.resetFields();
  const initData: any = initField();
  for (const key in initData) {
    form[key] = initData[key];
  }
  // 商品明细
  form.productCollection = props.goodsList;
  packageData.value = [];
};

// 提交表单
function handleSubmit() {
  formRef.value.validate().then((res: any) => {
    if (totalQty.value == 0) {
      ElMessage.error('不能补发空包裹');
      return;
    }

    if (res) {
      submitLoading.value = true;
      addRepeatPurchaseReplenishmentOrder(form)
        .then((res: any) => {
          if (res.code === 200) {
            ElMessage.success('新增成功');
            emits('ok');
            close();
            submitLoading.value = false;
          }
        })
        .catch(() => {
          submitLoading.value = false;
        });
    }
  });
}

// 根据产品类型
const getGoodsTypeByUsageType = (row: any) => {
  const type = row.usageType;
  const findx: any = props.goodsTypes.filter((item: any) => item.value === type);
  if (findx.length > 0) {
    return findx[0].label;
  }
  return '';
};

// 从套餐选择
function selectPackage() {
  selectGoodsPackageRef.value.show();
}

// 合计多少件
const totalQty = computed(() => form.productCollection.reduce((t, p: any) => t + (p.num || 0), 0));
// 合计金额
const totalAmount = computed(() =>
  form.productCollection.reduce((t: any, p: any) => t + (p.num || 0) * p.salePrice, 0)
);

function show(row: any) {
  if (row) {
    form.orderType = '2';
    form.relatedOrderId = row.orderNo;
  } else {
  }
  visible.value = true;
}

defineExpose({
  show
});

onMounted(() => {
  // 初始化类别数据
  customStore.initCustom();
});
</script>

<style scoped lang="scss">
.return-order-dialog {
  .query-form {
    margin-bottom: 15px;
  }

  .info-section {
    display: flex;
    flex-direction: column;
    gap: 16px;
    margin-bottom: 10px;
  }

  .section-title {
    border: 1px solid #ebebeb;
    padding: 40px 20px 20px 20px;
    box-sizing: border-box;
    border-radius: 4px;
    position: relative;
    margin-bottom: 10px;

    .label {
      position: absolute;
      display: inline-block;
      padding: 5px 10px;
      background: #ebebeb;
      font-size: 13px;
      margin-bottom: 10px;
      border-radius: 0 4px 4px 0;
      left: 0;
      top: 0;
    }

    .product-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      position: absolute;
      right: 20px;
      top: 10px;
    }
  }

  .total-bar {
    margin-top: 10px;
    padding-right: 10px;
    text-align: right;
    font-size: 14px;
    font-weight: 600;
    color: #333;

    .quantity {
      color: #409eff; // 蓝色，醒目
      margin-right: 10px;
    }

    .amount {
      color: #f56c6c; // 红色，高亮金额
      font-size: 16px;
    }

    .oldSalePrice {
      text-decoration: line-through;
    }

    .salePrice {
      margin-left: 10px;
    }
  }

  .empty-hint {
    padding: 12px;
    text-align: center;
    color: #999;
    font-size: 13px;
  }
}
</style>
